<template>
	<view class="">
		<view class="up_back">
			<!-- 锁板 -->
			<view class="" v-if="optType == 'lockPlate'">
				<view class="" v-if="mcuDevType == 6">
					<template v-if="ExVersion.length>0">
						<j-cell-group v-for="(item,index) in ExVersion" :key="index" :title="item.Partition">
							<j-cell title="当前版本" :tips="item.CurVersion" :more="false"> </j-cell>
							<j-cell title="新版本" :more="false">
								<view slot="tips" class="cell-tips" :class="item.newPartition?'new':''">
									{{item.newPartition? "有新版本" + item.newPartition : "最新版本" }}
									<image v-if="item.newPartition"
										src="https://statics.xmcsrv.net/weixin/update.png" />
								</view>
							</j-cell>
						</j-cell-group>
					</template>
					<template v-else>
						<j-cell-group>
							<j-cell title="当前版本" tips=" " :more="false"> </j-cell>
							<j-cell title="新版本" tips=" " :more="false"></j-cell>
						</j-cell-group>
					</template>
				</view>
				<j-cell-group v-if="mcuDevType == 3" :title="mcuNewVersion.Partition">
					<j-cell title="当前版本" :tips="mcuNewVersion.verDate" :more="false"> </j-cell>
					<j-cell title="新版本" :more="false">
						<view slot="tips" class="cell-tips" :class="mcuVersionStatus==1?'new':''">
							{{mcuVersionStatus == 1? "有新版本": mcuVersionStatus == 0 ? "最新版本": mcuVersionStatus == -1? "检查中...": "" }}
							<image v-if="mcuVersionStatus == 1" src="https://statics.xmcsrv.net/weixin/update.png" />
						</view>
					</j-cell>
				</j-cell-group>
				<button @tap="checkUpdate(mcuVersionStatus,'Mcu')" v-if="mcuVersionStatus == 1" type="operation"
					class="up_button">
					升级
				</button>
			</view>
			<!-- 猫眼 -->
			<view class="" v-if="optType == 'catEye'">
				<j-cell-group>
					<j-cell title="当前版本" class="lineFeed" :tips="currentVersion" :more="false"> </j-cell>
					<j-cell title="新版本" :more="false">
						<view slot="tips" class="cell-tips" :class="versionStatus==1?'new':''">
							{{versionStatus == 1? "有新版本": versionStatus == 0 ? "最新版本": versionStatus == -1? "检查中...": "" }}
							<image v-if="versionStatus == 1" src="https://statics.xmcsrv.net/weixin/update.png" />
						</view>
					</j-cell>
				</j-cell-group>
				<button @tap="checkUpdate(versionStatus)" v-if="versionStatus == 1" type="operation" class="up_button">
					升级
				</button>
			</view>
		</view>
		<j-modal :value="versionDialog" kText="确定" cancelText="一会再说" title="重要提示" @ok="onOk" @cancel="onCancel">
			<view slot="title" class="pop-title">升级过程中不能进行其他操作</view>
			<view slot="title" class="pop-title">请勿中途退出或按Home键</view>
			<view slot="title" class="pop-title">确认升级？</view>
		</j-modal>
		<j-modal :title="progress.title" :value="updateDialog" maskCloseAble="false" :showCancel="progress.status === 2"
			:showConfirm="progress.status !== 0" :okText="progress.status === 2 ? '重试' : '完成'" cancelText="取消"
			@cancel="cancelFn" @ok="retryFn">
			<view slot="content" class="progress-box">
				<view>
					<j-progress boxWidth="100" boxHeight="100" lineWidth="3"
						:bgColor="progress.status !== 2 ? '#B9E8E8' : '#f49590'" :fontShow="progress.fontShow"
						:progressColor="progress.status !== 2 ? '#FF0025' : '#f49590'" fontColor="#5677fc" fontSize="14"
						:percent="progress.percent">
						<image src="https://statics.xmcsrv.net/weixin/cha.png" class="cha"
							v-if="progress.status === 2" />
					</j-progress>
				</view>
				<view>
					<text style="color: #f49590;" v-if="progress.status === 0">升级过程中不能进行其他操作，请勿中途退出或按Home键</text>
					<text style="color: #f49590;" v-else-if="progress.status === 2" >失败原因：升级数据错误</text>
					<text v-else-if="progress.status === 1">设备重启中，请稍后访问</text>
				</view>
			</view>
		</j-modal>
		<j-modal :value="startDialog" :showCancel="false" :showConfirm="false">
			<view slot="title" class="flex align-center justify-between j-modal-title">
				<view style="width: 30%;" class=""></view>
				<view style="width: 30%;" class="hint">提示</view>
				<view style="width: 30%;text-align: end;" class="">
					<!-- <uni-icons @click="clearTimer" type="closeempty" size="25" /> -->
				</view>
			</view>
			<view slot="content" class="popupCont">
				<image class="bannerImg" src="https://statics.xmcsrv.net/weixin/operatingLock.png" mode="widthFix" />
				<view class="">请在门锁上按"8#"进入远程设置模式</view>
			</view>
		</j-modal>
	</view>
</template>

<script>
	import deviceLogin from '@/utils/deviceLogin.js';
	const { turnTenToSixteen } = require('@/utils/util.js');
	export default {
		data() {
			return {
				device: '', //设备信息
				versionDialog: false,
				updateDialog: false,
				versionStatus: -1, //主控版本状态
				mcuVersionStatus: -1, //锁板版本状态
				info: null, //主控版本信息
				mcuInfo: null, //锁板版本信息
				version: null, //主控最新版本号
				mcuVersion: null, //锁板最新版本号
				newVersion: '', //主控升级包
				mcuNewVersion: '', //锁板升级包
				selectType: null, //选中的升级类型
				progress: {
					ret: 0,
					title: '设备升级',
					status: 0, // 升级状态,0 升级中，1 成功， 2 失败
					fontShow: true,
					percent: 0,
				},
				McuCurrentVersion: '', //锁板当前版本
				currentVersion: '',
				optType: '', //升级类型
				status: '', //升级状态
				mcuDevType: null, //锁板设备类型 iot || ipc

				ExVersion: [], //锁板多模块显示数据组
				startDialog: false
			};
		},
		onLoad(opt) {
			//                         > 无新版本 > 展示版本号
			// 获取设备信息 > 获取版本信息 
			//                         > 有新版本 > 获取升级版本 > 升级 > 获取升级进度
			// 						          > 猫眼 >ipc > iot(取Modules)
			//                                > 锁板(多模块) > ipc > iot(取Modules)
			let enData = decodeURIComponent(opt.device)
			this.device = JSON.parse(enData)
			this.optType = opt.type;
			this.optStatus = opt.status;
			uni.setNavigationBarTitle({
				title: opt.type == 'catEye' ? "猫眼升级" : '锁具升级'
			});
			if(this.optType == 'catEye'){
				this.getDeviceDetail('SystemInfo') //猫眼 主控
			}else{
				this.getDeviceDetail('SystemInfoEx') // 锁板
			}
		},
		methods: {
			// 检查更新
			checkUpdate(versionStatus, type) {
				this.selectType = type
				if (versionStatus == 1) {
					if (type == 'Mcu') {
						this.startDialog = true;
						this.getDoorLockTransparent();
						return
					}
					this.versionDialog = true;
				} else if (versionStatus == 0) {
					uni.showToast({
						title: "已经是最新版本",
						icon: "none",
					});
				}
			},
			// 给设备端发start
			getDoorLockTransparent(status) {
				let data = {
					Name: 'OPDoorLockProCmd',
					OPDoorLockProCmd: {
						Cmd: "SyncDoorStatus",
						DoorStatus: {
							Status: 'Start1'
						}
					}
				};
				let token = this.device.token;
				getApp().globalData.api.doorLockTransparent(data, token, (result) => {
					uni.hideLoading()
					console.log('锁板升级', result);
					if (result.data.code == 2000) {
						let Err = turnTenToSixteen(result.data.data.DoorStatus.Err)
						if (Err === '0x00') {
							this.versionDialog = true;
						} else {
							uni.showToast({
								title: getApp().globalData.errCodeMsg.wakeUpLockBoardCodeMsg[Err] || result
									.data.msg,
								icon: 'none',
								duration: 2000
							});
						}
					} else {
						uni.showToast({
							title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data
								.msg,
							icon: 'none',
							duration: 2000
						});
					}
					this.clearTimer();
				}, false);
			},
			// 处理关闭倒计时
			clearTimer() {
				this.startDialog = false;
			},
			// 获取设备信息
			getDeviceDetail(type) {
				uni.showLoading({
					title: '获取设备基础信息...'
				});
				let token = this.device.token;
				const data = {
					Name: type,
				};
				getApp().globalData.api.getinfo(data, token, (result) => {
					uni.hideLoading()
					result = result.data
					console.log(result, type)
					let DevID;
					let DevType;
					let arr;
					let versionList;
					let obj;
					if (result.data.Ret && result.data.Ret == 100) {
						if (type == 'SystemInfo') {
							this.info = result.data.SystemInfo
							DevID = this.info.SoftWareVersion.split('.').join('')
							DevID = DevID.slice(7, ) //IOTHAVLS300800010ES30810 _HAVLS566503D9005
							DevType = DevID.slice(0, 3) === 'IOT' ? 'IOT' : 'IPC';
							this.currentVersion = this.info.SoftWareVersion
							if (DevType == 'IOT') {
								if (this.info.Modules) {
									arr = this.info.Modules
									versionList = arr.filter(item => {
										if (item.CurVersion) {
											return item.CurVersion
										}
									})
									obj = this.optObj(DevID, versionList[0].CurVersion, DevType)
									console.log(obj, 'iot主控的')
								}
							} else {
								obj = this.optObj(DevID, null, DevType)
								console.log(obj, 'ipc主控的')
							}
							this.version = {
								...obj
							}
							this.getVersion(obj)
							// this.getDeviceDetail('SystemInfoEx') // 锁板
						} else {
							this.mcuInfo = result.data.SystemInfoEx;
							if (this.mcuInfo.ExModules) {
								arr = this.mcuInfo.ExModules
								versionList = arr.filter(item => {
									if (item.CurVersion) {
										return item.CurVersion
									}
								})
								if (versionList.length > 0) {
									if (versionList[0].Modules.length > 0) {
										this.McuCurrentVersion = versionList[0].Modules[0].CurVersion
									}
								}
								DevID = versionList[0].UpDevID;
								DevType = DevID.slice(0, 3) === 'IOT' ? 'IOT' : 'IPC';
								DevType = DevType == 'IOT' ? 6 : 3
								this.mcuDevType = DevType
								if (versionList[0].CurVersion == 'V0.0') {
									console.log('没有锁板')
									obj = this.optObj(DevID, versionList[0].CurVersion, DevType)
									this.getVersion(obj)
									this.version = {
										...obj
									}
								} else {
									console.log('有锁板')
									obj = this.optObj(DevID, versionList[0].CurVersion, DevType, 'Mcu')
									this.ExVersion = versionList[0].Modules
									console.log(this.ExVersion)
									this.getVersion(obj, 'Mcu')
									this.mcuVersion = {
										...obj
									}
								}
								console.log(obj, '锁板的', this.version)
							}
						}
					} else if (result.data.Ret == 527) {
						//消息发给主控失败了，需要重新唤醒主控（650+3861L门锁用）
						this.wakeup(() => {
							this.getDeviceDetail(type)
						})
					} else {
						if (type == 'SystemInfo') {
							this.versionStatus = 0;
						} else {
							this.mcuVersionStatus = 0;
						}
					}
				}, false, false)
			},
			optObj(DevID, CurVersion = null, DevType = null, type) {
				const obj = {
					Name: 'OPVersionReq',
					OPVersionReq: {
						Expect: 0,
						Language: "Chinese",
						Manual: 1,
						SN: type ? null : this.device.deviceNo,
						DevID,
						CurVersion,
						DevType,
						UUID: this.device.deviceNo,
						Type: type || null
					},
				}
				return obj
			},
			// 获取设备版本
			getVersion(data, type) {
				let token = this.device.token;
				getApp().globalData.api.opdev(data, token, (res) => {
					this.$logs({
						info: "获取设备版本",
						res: {
							...res,
							SN: this.device.deviceNo,
						},
					});
					if (res.data.code == 2000) {
						res = res.data.data
						console.log(res, type ? '锁板获取设备升级版本信息' : '获取设备升级版本信息');
						if (res.Ret == 109) {
							if (type == 'Mcu') {
								this.mcuVersionStatus = 0;
							} else {
								this.versionStatus = 0;
							}
							return
						}
						if (res.Ret == 527) {
							//消息发给主控失败了，需要重新唤醒主控（650+3861L门锁用）
							this.wakeup(() => {
								this.getVersion(data, type)
							})
							return
						}
						// ipc锁板 没有返回Modules字段
						if (type == 'Mcu') { //锁板
							if (data.OPVersionReq.DevType == 3) { //ipc
								if (res.OPVersionRep.Date) { //有新版本
									this.mcuVersionStatus = 1
									this.mcuNewVersion = {
										verDate: res.OPVersionRep.Date,
										FileName: res.OPVersionRep.FileName,
										Partition: res.OPVersionRep.Partition
									};
								} else {
									this.mcuVersionStatus = 0;
								}
							} else { //iot
								if (res.OPVersionRep.Modules.length === 0) { //多模块
									this.mcuVersionStatus = 0;
								} else {
									this.mcuVersionStatus = 1;
									let Versionlist = []
									Versionlist = res.OPVersionRep.Modules.map(item => {
										const {
											Partition,
											FileName,
											Date,
											FileSize
										} = item;
										return {
											Partition,
											FileName,
											Date,
											FileSize
										};
									});
									Versionlist.forEach((item, index) => {
										this.ExVersion.forEach((izem, indez) => {
											if (item.Partition == izem.Partition) {
												izem.newPartition = item.Date
											}
										})
									})
									console.log(this.ExVersion, '新数组')
								}
							}
						} else { //猫眼
							console.log(data.OPVersionReq.DevType, '猫眼数据')
							if (data.OPVersionReq.DevType == 'IPC' || data.OPVersionReq.DevType == 3) {
								if (res.OPVersionRep) {
									this.versionStatus = 1;
									this.newVersion = {
										verDate: res.OPVersionRep.Date,
										FileName: res.OPVersionRep.FileName,
									};
								} else {
									this.versionStatus = 0;
								}
							} else {
								if (res.OPVersionRep.Modules.length > 0) {
									this.versionStatus = 1;
									this.newVersion = {
										verDate: res.OPVersionRep.Modules[0].Date,
										FileName: res.OPVersionRep.Modules[0].FileName,
									};
								} else {
									this.versionStatus = 0;
								}
							}
						}
					}
					this.$logs({
						info: "获取设备升级版本信息",
						res: {
							...res,
							SN: this.device.deviceNo,
						},
					});
				}, false, false);
			},
			// 确认升级
			onOk() {
				uni.setKeepScreenOn({
					keepScreenOn: true,
					success(res) {
						console.log('设置屏幕常亮成功onReady', res)
					},
					fail(err) {
						console.log(err)
					}
				})
				this.wakeup((res) => {
					deviceLogin(this.device, (result) => {
						this.updateVersion('', this.selectType)
					})
				})
				this.versionDialog = false
				this.updateDialog = true
			},
			// 低功耗设备唤醒
			wakeup(callback, decode = false, simple = false) {
				let data = {
					sn: this.device.deviceNo,
					hostedControl: "1", //是否唤醒主控（空值或0：不唤醒主控；1：唤醒主控）
				}
				getApp().globalData.api.wakeup(data, this.device.token, (result) => {
					callback(result);
				}, decode, simple);
			},
			onCancel() {
				this.versionDialog = false
			},
			// 重试
			retryFn() {
				console.log(this.progress, '点击升级框按钮')
				const status = this.progress.status
				if (status === 2) {
					// 升级失败，重试
					this.wakeup((res) => {
						console.log(res, '升级唤醒主控')
						deviceLogin(this.device, (result) => {
							this.updateVersion(1, this.selectType)
						})
						console.log('重试升级')
					})
				} else if (status === 1) {
					uni.switchTab({
						url: '/jvss/pages/device/home'
					});
					console.log(123)
				}
			},
			// 升级取消
			cancelFn() {
				this.updateDialog = false
				this.init()
				console.log('关闭弹窗')
			},
			// 初始化progress
			init() {
				this.progress = {
					ret: 0,
					title: '设备升级',
					status: 0, // 升级状态,0 升级中，1 成功， 2 失败
					fontShow: true,
					percent: 0,
				}
			},
			// 开始升级
			updateVersion(status, type) {
				console.log(type, this.mcuDevType)
				let token = this.device.token;
				let data;
				if (type == 'Mcu' && this.mcuDevType == 6) { //锁板多模块iot
					console.log('锁板多模块iot')
					data = {
						Name: "OPStartUpgradeReq",
						OPStartUpgradeReq: {
							UUID: this.mcuVersion.OPVersionReq.UUID,
							Manual: 1,
							Modules: this.mcuNewVersion,
							Type: "Mcu"
						},
					};
				} else { //锁板ipc
					console.log('锁板ipc,猫眼')
					const {
						Manual,
						UUID,
						DevID
					} = type == 'Mcu' ? this.mcuVersion.OPVersionReq : this.version.OPVersionReq;
					const {
						verDate,
						FileName
					} = type == 'Mcu' ? this.mcuNewVersion : this.newVersion;
					data = {
						Name: "OPStartUpgradeReq",
						OPStartUpgradeReq: {
							Manual,
							UUID,
							DevID,
							verDate,
							FileName,
						},
					};
				}
				console.log(data, '点击升级的data')
				this.$logs({
					info: '点击升级的data数据',
					res: {
						data,
						SN: this.device.deviceNo
					}
				})
				if (status) {
					this.progress.status = 0;
					this.progress.title = "设备升级";
					this.progress.fontShow = true;
					this.progress.percent = 0;
					this.progress.ret = 0;
				}
				getApp().globalData.api.opdev(
					data,
					token,
					(res) => {
						console.log(res, "开始升级设备");
						this.$logs({
							info: "开始升级日志信息",
							res: {
								...res,
								SN: this.device.deviceNo,
							},
						});
						if (res.data.code === 2000) {
							// 请求成功，改变状态，获取升级进度
							if (res.data.data.Ret == 100) {
								this.progress.status = 0;
								this.updateStatus = true;
								this.getUpgradeProgress();
							} else if (res.data.data.Ret == 527) {
								//消息发给主控失败了，需要重新唤醒主控（650+3861L门锁用）
								this.wakeup(() => {
									this.updateVersion(status, type)
								})
							} else {
								// 升级失败
								this.upgradeFaile();
							}
						} else {
							// 升级失败
							this.upgradeFaile();
						}
					},
					false,
					false
				);
			},
			// 升级失败
			upgradeFaile() {
				this.progress.status = 2;
				this.progress.title = "升级失败";
				this.progress.fontShow = false;
				this.progress.percent = 0;
			},
			// 获取升级进度
			getUpgradeProgress() {
				let token = this.device.token;
				let data = {
					Sn: this.device.deviceNo,
				};
				getApp().globalData.api.getUpgradeProgress(
					data,
					token,
					(res) => {
						this.$logs({
							info: "获取升级进度信息",
							res: {
								...res,
								SN: this.device.deviceNo,
							},
						});
						if (res.data.code !== 2000) {
							// 更新失败
							this.upgradeFaile();
						} else {
							if (res.data.data.Ret === 515) {
								// 升级成功
								this.progress.status = 1;
								this.progress.title = "升级成功";
								this.progress.fontShow = true;
								this.progress.percent = 100;
							} else if (res.data.data.Ret === 514) {
								this.upgradeFaile();
							} else {
								// 正在升级
								this.getUpgradeProgress();
								if (res.data.data.UpgradeType == 0) {
									this.progress.title = "正在升级中";
								} else if (res.data.data.UpgradeType == 1) {
									this.progress.title = "正在下载";
								}
								this.progress.percent = res.data.data.Ret;
							}
						}
						console.log(res.data.data, "获取升级进度111");
					},
					false,
					false
				);
			},
		},
	};
</script>

<style lang="scss">
	.up_back {
		background-color: #fff;
		margin: 20rpx auto;
		width: 96%;
		border-radius: 8px;
		overflow: hidden;
	}

	.up_button {
		width: 90% !important;
		height: 70rpx;
		border-radius: 35rpx;
		border: 2px solid #B9B9B9 !important;
		font-size: 30rpx;
		text-align: center;
		margin: 10px auto;
		line-height: 70rpx;
	}

	.up_button::after {
		display: none;
	}

	.cell-tips {
		font-size: 24rpx;
		color: #999999;
		max-width: 62vw;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;

		image {
			width: 36rpx;
			height: 36rpx;
			margin-left: -12rpx;
		}
	}

	.new {
		color: #FF0025;
		display: flex;
		align-items: center; //对齐
		justify-content: center; //居中

		image {
			width: 36rpx;
			height: 36rpx;
			margin-left: -12rpx;
		}
	}

	.circular-container {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.pop-title {
		padding-top: 16rpx;
	}

	.progress-box {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.cha {
		width: 60rpx;
		height: 60rpx;
		position: absolute;
	}

	.lineFeed {
		/deep/.cell-tips {
			word-wrap: break-word;
			/*允许长单词换行到下一行*/
			word-break: break-all;
			/*这个参数根据需要来决定要不要*/
			overflow: hidden;
			/*这个参数根据需要来决定要不要*/
			white-space: break-spaces;
			text-align: end;
		}
	}

	.popupCont {
		.countDown {
			font-size: 30rpx;
			font-weight: bold;
			color: #FF0025;
		}
	}

	.bannerImg {
		width: 80%;
		height: auto;
	}
</style>